package com.fresh.fresh.service.lmpI;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fresh.fresh.dao.Cart;
import com.fresh.fresh.dao.Commodity;
import com.fresh.fresh.dao.Orders;
import com.fresh.fresh.dao.Item;
import com.fresh.fresh.mapper.OrderItemMapper;
import com.fresh.fresh.mapper.OrderMapper;
import com.fresh.fresh.service.CartService;
import com.fresh.fresh.service.OderService;
import com.fresh.fresh.service.OrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OderService {

    @Autowired
    OrderItemService orderItemService;
    @Resource
    CartService cartService;
    @Resource
    OrderMapper orderMapper;
    @Resource
    OrderItemMapper orderItemMapper;

    @Override
    public void addGoods(List<Cart> carts) {
        Orders order = new Orders();
        order.setUid(IdUtil.fastSimpleUUID());
        for (Cart cart : carts) {
            order.setUserId(cart.getUserId());
            order.setCommodityId(cart.getCommodityId());
            save(order);
        }

        //把前端传过来的数据保存在item
        for (Cart cart : carts) {
            Item orderItem = new Item();
            orderItem.setOrderId(order.getId());
            orderItem.setImg(cart.getImg());
            orderItem.setPrice(cart.getPrice());
            orderItem.setCommodityId(cart.getCommodityId());
            orderItem.setNum(cart.getNum());
            orderItem.setName(cart.getName());
            orderItemService.save(orderItem);

            //下单成功后删除购物车的商品
            cartService.removeById(cart.getId());
        }
    }

    //删除订单
    @Override
    public void deleteOder(Integer id) {
        this.baseMapper.deleteById(id);

        orderItemMapper.deleteItem(id);
    }

    //获取对应用户的订单
    @Override
    public List<Orders> getFindAll(Integer userId) {
        List<Orders> ordersList = orderMapper.getUserOrder(userId);
        for (Orders orders : ordersList) {
            Integer orderId = orders.getId();
            List<Item> itemList = orderItemService.list(new QueryWrapper<Item>().eq("order_id", orderId));
            orders.setOrderItem(itemList);
        }
        return ordersList;
    }

    @Override
    public void updateOrder(Orders orders) {
        updateById(orders);
    }




}
